
--[[句柄管理器]]
handle_manager_class = {}

function handle_manager_class:create()
    local handle_manager = {
        top      = 1,
        stack    = { },
        map      = { },
        id_table = { },
        __index  = self,
    }
    setmetatable(handle_manager, handle_manager)
    return handle_manager
end 

function handle_manager_class:allocate()
    local id = self.top
    local stack = self.stack
    if #stack == 0 then 
        id = self.top
        self.top = self.top + 1
    else
        id = stack[#stack]
        table.remove(stack,#stack)
        self.map[id] = nil
    end
    self.id_table[id] = 1
    return id
end 

function handle_manager_class:free(id)
    if self.id_table[id] == nil and self.map[id] ~= nil then
        log.error('重复回收',id)
    elseif self.id_table[id] == nil then
        print('非法回收',id)
    end
    if self.map[id] == nil and self.id_table[id] ~= nil then
        self.map[id] = 1
        self.id_table[id] = nil 
        table.insert(self.stack,id)
    end
end 


function extend(parent_class, child_class)
    local tbl = {}
    local mt = getmetatable(parent_class)
    if mt ~= nil then
        tbl.__tostring = mt.__tostring
        tbl.__call = mt.__call
    end
    child_class.__index = parent_class
    setmetatable(child_class,child_class)
    return child_class
end


function extends(...)
    local parents = {...}
	local count = select('#',...)
    local parent_class = parents[1]
    return function(child_class)
        local tbl = {}
        local mt = getmetatable(parent_class)
        if mt ~= nil then
            tbl.__call = mt.__call
            tbl.__tostring = mt.__tostring
        end
        if count == 1 then
            tbl.__index = parent_class
        else
            tbl.__index = function (_,key)
                for i = 1,count do
                    local v = parents[i]
                    if v and v[key] then
                        return v[key]
                    end
                end
            end
        end
        setmetatable(child_class,tbl)
        return child_class
    end
end

-- function Class(name)
--     local new = {
--         type = name,
--         __index = {},
--         __tostring = function(self)
--             return ("class:%s"):format(self.type)
--         end,
--         __call = function(self, data) 
--             for k,v in pairs(data) do 
--                 self[k] = v 
--             end 
--             return self 
--         end,
--     }
--     setmetatable(new, new)
--     return new
-- end 

-- function extends(child_class, parent_class)
--     child_class.__tostring = parent_class.__tostring
--     child_class.__call = parent_class.__call
--     setmetatable(child_class.__index, parent_class)
--     return child_class
-- end 
